import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import dayjs from 'dayjs';
import { totaldata } from '@/api/account';
import './Home.css';

const Home = () => {
  const chartRef = useRef(null);
  const [chartData, setChartData] = useState({
    xData: [], // 初始化空数组防止undefined错误
    orderData: [],
    amountData: []
  });
  const myChartRef = useRef(null); // 使用useRef保存echarts实例

  // 绘制图表函数
  const drawChart = () => {
    if (!chartRef.current) return;
    
    // 如果已有实例则先销毁
    if (myChartRef.current) {
      myChartRef.current.dispose();
    }
    
    // 初始化图表
    myChartRef.current = echarts.init(chartRef.current);
    const option = {
      title: {
        text: '数据统计',
        subtext: '日期:' + dayjs().format('YYYY-MM-DD'),
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['订单', '销售额']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: chartData.xData
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '订单',
          type: 'line',
          data: chartData.orderData,
          itemStyle: {
            color: '#5470C6' // 给线条添加颜色
          }
        },
        {
          name: '销售额',
          type: 'line',
          data: chartData.amountData,
          itemStyle: {
            color: '#91CC75' // 给线条添加颜色
          }
        }
      ]
    };
    myChartRef.current.setOption(option);
  };

  // 处理窗口大小变化
  const handleResize = () => {
    if (myChartRef.current) {
      myChartRef.current.resize();
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await totaldata();
       // console.log('获取到的数据:', res); // 调试用
        setChartData({
          xData: res.xData || [],
          orderData: res.orderData || [],
          amountData: res.amountData || []
        });
      } catch (error) {
        console.error('获取数据失败:', error);
        // 使用模拟数据作为fallback
        setChartData({
          xData: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          orderData: [120, 132, 101, 134, 90, 230, 210],
          amountData: [220, 182, 191, 234, 290, 330, 310]
        });
      }
    };
    fetchData();

    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
      if (myChartRef.current) {
        myChartRef.current.dispose();
      }
    };
  }, []);

  // 数据变化时重新绘制图表
  useEffect(() => {
    if (chartData.xData.length > 0) { // 确保有数据再绘制
      drawChart();
    }
  }, [chartData]);

  return (
    <div className="home-container">
      <h2>数据统计</h2>
      <div 
        ref={chartRef} 
        style={{
          width: '100%',
          height: '500px',
          minHeight: '300px',
          border: '1px solid #eee',
          borderRadius: '4px',
          padding: '10px'
        }}
      />
    </div>
  );
};

export default Home;